import { type PaginationProps } from "@pureadmin/table";
import { computed, onMounted, reactive, ref } from "vue";
import { getLoginLogList } from "@/api/log";
import { LoginLog } from "@/api/model/logModel";

export function useOperator() {
  const form: LoginLog = reactive({
    size: 10,
    current: 1,
  });
  const dataList = ref([]);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      width: 70,
      hide: ({ checkList }) => !checkList.includes("序号列"),
    },
    {
      label: "登录账号",
      prop: "loginName",
      minWidth: 80,
    },
    {
      label: "登录设备",
      prop: "loginDevice",
      minWidth: 80,
    },
    {
      label: "登录结果",
      minWidth: 50,
      prop: "status",
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          type={row.status === "失败" ? "danger" : "success"}
          effect="plain"
        >
          {row.status}
        </el-tag>
      ),
    },
    {
      label: "说明",
      prop: "msg",
      showOverflowTooltip: true,
      cellRenderer: ({ row }) => {
        return JSON.parse(row.msg).msg;
      },
    },
    {
      label: "登录IP",
      minWidth: 80,
      prop: "remoteAddr",
    },
    {
      label: "登录地址",
      minWidth: 80,
      prop: "ipRegion",
    },
    {
      label: "登录时间",
      minWidth: 80,
      prop: "created",
    },
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary",
    ];
  });

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    form.current = pagination.currentPage;
    form.size = pagination.pageSize;
    const { records, total } = await getLoginLogList(form);
    dataList.value = records;
    pagination.total = total;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    pagination.currentPage = 1;
    pagination.pageSize = 10;
    onSearch();
  };

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    buttonClass,
    onSearch,
    resetForm,
    handleSizeChange,
    handleCurrentChange,
  };
}
